<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :destroy-on-close="true"
      :width="!props.isReadonly ? '1100px' : '1100px'"
      :align-center="true"
      draggable
      @close="closeDialog"
      style="min-width: 1100px"
      class="maxhDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120"
        v-show="!props.isReadonly"
        style="width: 99%"
      >
        <!-- <h4 class="mb-[20px] mt-[0px]">基本数据</h4> -->
        <div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="作业项编号" prop="sopItemCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sopItemCode"
                  placeholder="请输入作业项编号"
                  clearable
                />
                <span v-else>{{ formData.sopItemCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业项名称" prop="sopItemName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sopItemName"
                  placeholder="请输入作业项名称"
                  clearable
                />
                <span v-else>{{ formData.sopItemName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业部位" prop="sopItemPosition">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sopItemPosition"
                  placeholder="请输入作业部位"
                  clearable
                />
                <span v-else>{{ formData.sopItemPosition }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="作业方法" prop="sopItemMethod">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sopItemMethod"
                  placeholder="请输入作业方法"
                  clearable
                />
                <span v-else>{{ formData.sopItemMethod }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业工具" prop="sopItemTool">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sopItemTool"
                  placeholder="请输入作业工具"
                  clearable
                />
                <span v-else>{{ formData.sopItemTool }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="作业标准" prop="sopItemStandardValue">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sopItemStandardValue"
                  placeholder="请输入作业标准"
                  clearable
                />
                <span v-else>{{ formData.sopItemStandardValue }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="是否需要图片" prop="sopImage">
                <el-radio-group v-model="formData.sopImage">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否需要视频" prop="sopVideo">
                <el-radio-group v-model="formData.sopVideo">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否必须执行" prop="sopExecute">
                <el-radio-group v-model="formData.sopExecute">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group v-model="formData.enabled">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  type="textarea"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  show-word-limit
                  :maxlength="250"
                  :autosize="{ minRows: 2, maxRows: 3 }"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">标准值</el-divider>
          <div>
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="标准值类型"
                  prop="standardValue"
                  class="standard-value"
                >
                  <el-radio-group v-model="formData.standardValue">
                    <el-radio-button
                      v-for="item in dictionaryStore.filterDictList(
                        'standardValue'
                      )"
                      :label="item.value"
                      :value="item.value"
                      :key="item.value"
                    >
                      {{ item.label }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="flex justify-end">
                <el-button
                  v-if="formData.standardValue == 2"
                  type="success"
                  plain
                  @click="handleAdd"
                >
                  <i-ep-plus />
                  新增</el-button
                >
              </el-col>
            </el-row>
            <el-row v-if="formData.standardValue == 2" class="formTable">
              <el-col :span="16">
                <el-table
                  :data="formData.details"
                  style="width: calc(100% - 36px); margin-left: 36px"
                  :key="Math.random"
                  border
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    align="center"
                    width="100"
                  />
                  <el-table-column
                    label="标准值"
                    props="standardValue"
                    min-width="150"
                  >
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.standardValue'"
                        :rules="rules.sonstandardValue"
                        label-width="0"
                      >
                        <el-input
                          v-if="!props.isReadonly"
                          v-model="row.standardValue"
                          placeholder="请输入标准值"
                          clearable
                        />
                        <span v-else>{{ row.standardValue }}</span>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="结果" props="resultValue" width="150">
                    <template #default="{ $index, row }">
                      <el-form-item
                        :prop="'details.' + $index + '.resultValue'"
                        :rules="rules.sonresultValue"
                        label-width="0"
                      >
                        <el-select
                          v-model="row.resultValue"
                          placeholder="请选择结果"
                          clearable
                        >
                          <el-option label="正常" value="1" />
                          <el-option label="异常" value="0" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    width="100"
                    v-if="!props.isReadonly"
                  >
                    <template #default="scope">
                      <el-button
                        :disabled="formData.details.length < 2"
                        type="danger"
                        link
                        @click.stop="handleDelete(scope.$index)"
                        class="mt-[0px]"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <el-row v-if="formData.standardValue == 1">
              <el-col :span="8">
                <div class="flex">
                  <div class="w-[120px] standard-title">标准值范围</div>

                  <el-form-item
                    prop="standardMinValue"
                    labelWidth="0"
                    class="flex-1"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.standardMinValue"
                      placeholder="最小值"
                      clearable
                    />
                    <span v-else>{{ formData.standardMinValue }}</span>
                  </el-form-item>
                  <div class="standard-range">~</div>
                  <el-form-item
                    prop="standardMaxValue"
                    labelWidth="0"
                    class="flex-1"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.standardMaxValue"
                      placeholder="最大值"
                      clearable
                    />
                    <span v-else>{{ formData.standardMaxValue }}</span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标准值单位" prop="standardValueUnit">
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="formData.standardValueUnit"
                    placeholder="请输入标准值单位"
                    clearable
                  />
                  <span v-else>{{ formData.standardValueUnit }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <el-divider content-position="left">图片</el-divider>

          <div class="pl-[30px] pr-[30px]">
            <CommonUploadFile
              :isRead="props.isReadonly"
              :files="formData.images"
              accept=".jpg,.png,.jpeg"
              @update-files="updateFormFiles"
            />
          </div>
        </div>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        title=""
        :column="3"
        size="large"
        border
        style="width: 99%"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业项编号</div>
          </template>
          {{ formData.sopItemCode || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业项名称</div>
          </template>
          {{ formData.sopItemName || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业部位</div>
          </template>
          {{ formData.sopItemPosition || "" }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">作业方法</div>
          </template>
          {{ formData.sopItemMethod || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业工具</div>
          </template>
          {{ formData.sopItemTool || "" }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">作业标准</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.sopItemStandardValue || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否需要图片</div>
          </template>
          <el-tag v-show="formData.sopImage === '1'" type="">是</el-tag>
          <el-tag v-show="formData.sopImage !== '1'" type="info">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否需要视频</div>
          </template>
          <el-tag v-show="formData.sopVideo === '1'" type="">是</el-tag>
          <el-tag v-show="formData.sopVideo !== '1'" type="info">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否必须执行</div>
          </template>
          <el-tag v-show="formData.sopExecute === '1'" type="">是</el-tag>
          <el-tag v-show="formData.sopExecute !== '1'" type="info">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          {{ formData.remarks || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">标准值类型</div>
          </template>
          {{
            dictionaryStore.filterDictName(
              "standardValue",
              formData.standardValue
            )
          }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.standardValue == 2" :span="3">
          <template #label>
            <div class="cell-item">标准值</div>
          </template>
          <div>
            <p
              v-for="(item, index) in formData.details"
              :key="index"
              class="mt-[6px] mb-[6px]"
            >
              <span>{{ index + 1 }}、</span>
              <span>{{ item.standardValue }}</span>
              <span v-if="item.resultValue == '1'" class="ml-[24px]"
                ><el-icon color="#67C23A" size="16" style="vertical-align: sub"
                  ><CircleCheckFilled
                /></el-icon>
                正常</span
              >
              <span v-if="item.resultValue == '0'" class="ml-[24px]"
                ><el-icon color="#F56C6C" size="16" style="vertical-align: sub"
                  ><InfoFilled
                /></el-icon>
                异常</span
              >
            </p>
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.standardValue == 1">
          <template #label>
            <div class="cell-item">标准值范围</div>
          </template>
          {{ formData.standardMinValue }} ~ {{ formData.standardMaxValue }}
        </el-descriptions-item>
        <el-descriptions-item v-if="formData.standardValue == 1" :span="2">
          <template #label>
            <div class="cell-item">标准值单位</div>
          </template>
          {{ formData.standardValueUnit }}
        </el-descriptions-item>

        <el-descriptions-item :span="3">
          <template #label>
            <div class="cell-item">图片</div>
          </template>
          <div v-if="formData.images && formData.images.length">
            <CommonUploadFile
              :showText="false"
              :isRead="props.isReadonly"
              :files="formData.images"
              @update-files="updateFormFiles"
            />
          </div>
          <div v-else>无</div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { CircleCheckFilled, InfoFilled } from "@element-plus/icons-vue";
import { validateIsNumber } from "@/utils/commonHooks";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSSOPITEMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
  standardId: {
    type: String,
    default: "",
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
const formRef = ref(ElForm);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
let formData = reactive({
  id: "",
  version: "",
  sopItemCode: "",
  sopItemName: "",
  sopItemPosition: "",
  sopItemMethod: "",
  sopItemTool: "",
  sopItemStandardValue: "",
  sopImage: "0",
  sopVideo: "0",
  sopExecute: "0",
  standardValue: 1,
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  standardMaxValue: "",
  standardMinValue: "",
  standardValueUnit: "",
  details: [
    // {
    //   id: "",
    //   version: "",
    //   sopItemId: "",
    //   standardValue: "",
    //   resultValue: "",
    //   remarks: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    //   enabled: "",
    //   deleted: "",
    // },
  ],
  assetKind: props.assetKind,
  standardId: props.standardId,
  images: [],
});

/** rules规则 */
const rules = reactive({
  sopItemCode: [
    { required: true, message: "请输入作业项编号", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  sopItemName: [
    { required: true, message: "请输入作业项名称", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  // sopItemPosition: [
  //   { required: true, message: "请选择作业项部位", trigger: "change" },
  // ],
  sopItemPosition: [
    { required: false, message: "请输入作业项部位", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  sopItemMethod: [
    { required: false, message: "请输入作业方法", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  sopItemStandardValue: [
    { required: false, message: "请输入作业标准", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  sopItemTool: [
    { required: false, message: "请输入作业工具", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  sopImage: [
    { required: true, message: "请选择是否需要图片", trigger: "change" },
  ],
  sopVideo: [
    { required: true, message: "请选择是否需要视频", trigger: "change" },
  ],
  sopExecute: [
    { required: true, message: "请选择是否立即执行", trigger: "change" },
  ],
  standardValue: [
    { required: false, message: "请选择标准值类型", trigger: "change" },
  ],
  remarks: [
    { message: "请输入备注", trigger: "blur" },
    { max: 255, message: "不能超过255个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "change" }],
  standardMaxValue: [
    { required: false, message: "请输入最大值", trigger: "blur" },
    {
      validator: validateIsNumber,
      trigger: "blur",
    },
  ],
  standardMinValue: [
    { required: false, message: "请输入最小值", trigger: "blur" },
    {
      validator: validateIsNumber,
      trigger: "blur",
    },
  ],
  standardValueUnit: [
    { required: false, message: "请输入标准值单位", trigger: "blur" },
    { max: 10, message: "不能超过10个字符", trigger: "blur" },
  ],
  sonstandardValue: [
    { required: false, message: "请输入标准值", trigger: "blur" },
    { max: 32, message: "不能超过32个字符", trigger: "blur" },
  ],
  sonresultValue: [
    { required: false, message: "请选择结果", trigger: "change" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  sopItemId: "",
  standardValue: "",
  resultValue: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    } else {
      formData.enabled = 1;
      formData.assetKind = props.assetKind;
      formData.standardId = props.standardId;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.sopItemCode = "";
  formData.sopItemName = "";
  formData.sopItemPosition = "";
  formData.sopItemMethod = "";
  formData.sopItemTool = "";
  formData.sopItemStandardValue = "";
  formData.sopImage = "0";
  formData.sopVideo = "0";
  formData.sopExecute = "0";
  formData.standardValue = 1;
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.standardMaxValue = "";
  formData.standardMinValue = "";
  formData.standardValueUnit = "";
  formData.standardId = "";
  formData.assetKind = props.assetKind;
  formData.images = [];
  formData.standardId = props.standardId;
}

const loading = ref(false);

/** 标准作业项保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      clearStandardValue();
      if (
        formData.standardValue == 1 &&
        Number(formData.standardMaxValue) < Number(formData.standardMinValue)
      ) {
        ElMessage.error("标准值范围最大值不能小于最小值");
        return false;
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/qmssopitem/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

// 清空选择测量、非测量后产生的无效数据
function clearStandardValue() {
  if (formData.standardValue == 2) {
    formData.standardMaxValue = "";
    formData.standardMinValue = "";
    formData.standardValueUnit = "";
  } else {
    formData.details = [
      // {
      //   id: "",
      //   version: "",
      //   sopItemId: "",
      //   standardValue: "",
      //   resultValue: "",
      //   remarks: "",
      //   createTime: "",
      //   createdUserId: "",
      //   createdUserName: "",
      //   lastUpdateTime: "",
      //   lastUpdatedUserId: "",
      //   lastUpdatedUserName: "",
      //   enabled: "",
      //   deleted: "",
      // },
    ];
  }
}

async function getdetails() {
  let sondetails = await request({
    url: "/qms/qmssopitem/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 图片处理
function updateFormFiles(val: []) {
  formData.images = val;
}
</script>

<style lang="scss" scoped>
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}

.standard-title {
  display: flex;
  justify-content: flex-end;
  padding-right: 12px;
  line-height: 33px;
  // &::before {
  //   content: "*";
  //   color: var(--el-color-danger);
  //   margin-right: 4px;
  // }
}
.standard-range {
  line-height: 33px;
  padding: 0 5px;
}
.el-form-item--default {
  margin-bottom: 15px;
}
:deep(.el-table td.el-table__cell) {
  padding: 0;
}
:deep(.el-table .el-form-item) {
  margin: 13px 0;
}
:deep(.el-table .el-form-item__error) {
  padding-top: 1px !important;
  font-size: 11px !important;
}
</style>
